package com.example.demo.service;

import com.example.demo.entity.Category;
import com.example.demo.mapper.CategoryMapper;
import com.example.demo.model.Result;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CategoryService {
    private CategoryMapper categoryMapper;

    public Result getAllCategory(){
        List<Category> categories = categoryMapper.selectList(null);
//        System.out.println("---------------------------");
//        System.out.println(categories);

        MultiValueMap<Integer , Category> multiValueMap = new LinkedMultiValueMap();

        List<Category> rootCategory = categories.stream().filter(category -> {
            Integer parentId = category.getParentId();
            if (parentId != 0){
                List<Category> depts = multiValueMap.get(parentId);
                if (depts == null){
                    depts = new ArrayList<>();
                    depts.add(category);
                    multiValueMap.put(parentId,depts);
                }else {
                    depts.add(category);
                }
            }
            return parentId == 0;
        }).collect(Collectors.toList());

        rootCategory.sort((d1,d2) -> d1.getCategoryIevel() - d2.getCategoryIevel());

        departmentTree(rootCategory,multiValueMap);

        return Result.buildSuccess(rootCategory);
    }


    public void departmentTree(List<Category> categories, MultiValueMap<Integer,Category> multiValueMap){
        categories.forEach(category -> {
            Integer id = category.getId();//获取部门id，找子部门
            List<Category> children = multiValueMap.get(id);//获取所有的子部门

            if (null != children && children.size()>0){
                children.sort((d1,d2) -> d1.getCategoryIevel() - d2.getCategoryIevel());
                category.setChildren(children);
                departmentTree(children,multiValueMap);
            }
        });
    }
}